package com.douqu.game.plantwar.core.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.douqu.game.plantwar.core.commons.AppConstant;
import sun.rmi.runtime.Log;

import java.util.Calendar;
import java.util.Date;
import java.util.Map;

public class JWTUtils {

    public static final String SECRET = "plantwar";
    public static final Algorithm algorithm = Algorithm.HMAC256(SECRET);
    public static final JWTVerifier verifier = JWT.require(algorithm).build();

    public static String createToken(long roleId, String account, String head, String nickName) {
        Calendar iatTime = Calendar.getInstance();
        iatTime.add(Calendar.HOUR, 1);
        Date expiresDate = iatTime.getTime();
        return JWT.create().withClaim(AppConstant.ROLE_ID_PREX, roleId).withClaim(AppConstant.ACCOUNT, account)
                .withClaim(AppConstant.HEAD, head).withClaim(AppConstant.NICK_NAME, nickName).withExpiresAt(expiresDate)
                .sign(algorithm);
    }

    public static Map<String, Claim> verify(String token) {
        try {
            return verifier.verify(token).getClaims();
        } catch (TokenExpiredException e) {
            LogUtils.error("token 已过期");
        } catch (Exception e) {
            LogUtils.error("token 异常");
        }
        return null;
    }
}
